﻿using Assets.Core.Common.Web;
using Masuit.Tools;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Nucleic.Core.DoMain;
using Nucleic.Core.Utils;
using Nucleic.Web.Models.PatientInfo;
using SqlSugar;

namespace Nucleic.Web.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class PatientInfoController : ControllerBase
    {
        /// <summary>
        /// 新建/更新 患者信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        /// 
        [HttpPost]
        [Route("Create")]

        public Result Create(PatientInfoCreateInput input)
        {
            //兼容之前的版本,没有isMainland参数
            if (string.IsNullOrEmpty(input.isMainland))
            {
                input.isMainland = "1";
            }
            if (input.isMainland=="1")
            {
                if (input.idnum.MatchIdentifyCard() == false)
                {
                    return Result.fail("身份证不合法!");
                }
                if (string.IsNullOrEmpty(input.tel) ||input.tel.Length!=11||!input.tel.StartsWith('1'))
                {
                    return Result.fail("手机号不合法!");
                }
            }
           
            var pat = 0;
            patient_info patient_Info = SqlSugarFactory.Instance.Queryable<patient_info>().First(it => it.idnum == input.idnum);
            if (patient_Info == null)
            {
                patient_Info = new patient_info()
                {
                    name = input.name,
                    idnum = input.idnum,
                    addr = input.addr,
                    tel = input.tel,
                    sex = input.sex,
                    classification = 1
                };
                pat = SqlSugarFactory.Instance.Insertable(patient_Info).ExecuteReturnIdentity();
            }
            else
            {
                pat = patient_Info.pat_id;
                patient_Info.name = input.name;
                patient_Info.idnum = input.idnum;
                patient_Info.addr = input.addr;
                patient_Info.tel = input.tel;
                patient_Info.sex = input.sex;
                SqlSugarFactory.Instance.Updateable(patient_Info).ExecuteCommand();
            }
            return Result.success(pat);
        }

        /// <summary>
        /// 输入身份证后查询患者信息
        /// </summary>
        /// <param name="idnum">身份证</param>
        /// <returns></returns>
        /// 
        [HttpPost]
        [Route("Query")]
        public Result<patient_info> Query(string idnum)
        {
            var patient = SqlSugarFactory.Instance.Queryable<patient_info>().First(it => it.idnum == idnum);
            return Result<patient_info>.success(patient);
        }

    
    }
}
